package com.jp.knowledge.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.NestedScrollingParentHelper;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.iflytek.cloud.SpeechError;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.adapter.AttentionAdapter;
import com.jp.knowledge.adapter.SearchHistoryAdapter;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.db.DBHelper;
import com.jp.knowledge.dialog.CommDialog;
import com.jp.knowledge.dialog.SearchPopuWindow;
import com.jp.knowledge.fragment.SearchAttentionFragment;
import com.jp.knowledge.fragment.SearchDetailFragment;
import com.jp.knowledge.fragment.SearchDetailUiFragment;
import com.jp.knowledge.fragment.SearchRecommendFragment;
import com.jp.knowledge.fragment.SearchTeamCircleFragment;
import com.jp.knowledge.model.HeadLine;
import com.jp.knowledge.model.SearchKey;
import com.jp.knowledge.my.util.MyUtil;
import com.jp.knowledge.util.VoiceInputUtils;
import com.jp.knowledge.view.SearchBgView;
import com.jp.knowledge.view.TabHostWrapPagerView;
import com.jp.knowledge.view.TabView;

import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import rx.Observable.OnSubscribe;
import rx.Observer;
import rx.Subscriber;

/**
 * 搜索activity
 */
public class SearchActivity extends SlidingActivity implements View.OnClickListener {

    @ViewInject(R.id.head)
    private LinearLayout headLayout;
    @ViewInject(R.id.activity_search)
    private LinearLayout searchActivity;
    @ViewInject(R.id.search)
    protected EditText searchEdit;
    @ViewInject(R.id.search_goback)
    private ImageView searchGoback;
    @ViewInject(R.id.cancle_search)
    private TextView cancleSearch;//取消搜索 返回 前一个页面
    @ViewInject(R.id.search_del)
    private ImageView delSearchIcon;//删除搜索关键字   取消当前页面搜索
    @ViewInject(R.id.search_voice_input)
    private ImageView voiceInputIcon;
    @ViewInject(R.id.search_history_rv)
    private RecyclerView searchHistoryRv;
    @ViewInject(R.id.search_history_view)
    private NestedScrollView searchHistoryView;
    @ViewInject(R.id.search_history_clear)
    private TextView searchHistoryTv;
    @ViewInject(R.id.start_search)
    private LinearLayout startSearch;
    @ViewInject(R.id.content_fragment)
    protected LinearLayout content;
    @ViewInject(R.id.them_tab_nav)
    protected RecyclerView recycleView;
    @ViewInject(R.id.tab_view)
    protected TabView tabView;
    @ViewInject(R.id.view_page)
    protected TabHostWrapPagerView pager;
    @ViewInject(R.id.search_bg_view)
    protected SearchBgView searchBgView;

    private String infoId;
    private int type;

    protected String id;//搜索使用的id

    private List<HeadLine> headLines;
    private AttentionAdapter attentAdapter;

    private static int lastPosition = 0;//上一个选中位置
//    protected String[] itemNames = new String[]{"头条", "公司", "产品", "人物", "界面", "文库", "行业大观察", "每日评说", "全民推荐", "团队圈"};
//    protected int[] types = new int[]{1, 3, 8, 4, 15, -1, 21, 17, 11, 16};
//    protected String[] itemNames = new String[]{"产品", "公司", "人物", "头条", "行业", "文库", "界面"};
//    protected int[] types = new int[]{8, 3, 4, 1, 21, -1, 15};
    protected String[] itemNames = new String[]{"知识", "文库", "素材"};
    protected int[] types = new int[]{13, -1, 15};

    private String curKey;
    private Callback callBack;
    protected List<Fragment> fragments;
    private InputMethodManager  inputManager;

    private SearchPopuWindow  searchWindow;
    private String lastKey;//上一个关键字
    private boolean handSearch;//执行搜索后设为true;
    private CommDialog clearHistoryDialog;

    private SearchHistoryAdapter searchHistoryAdapter;
    private List<SearchKey> searchHistorys;
    private Observer<List<SearchKey>> readDbObserver;
    private OnSubscribe saveDbOnSubscribe;

    protected int action;
    protected int level;

    public static void gotoSearch(Context context, String key, int type){
        context.startActivity(new Intent(context, SearchActivity.class)
                .putExtra("key", key).putExtra("type", type));
    }

    @Override
    protected int getResourceId() {
        return R.layout.activity_search;
    }

    public void setCallBack(Callback callBack) {
        this.callBack = callBack;
    }

    @Override
    protected void init() {
        action = getIntent().getIntExtra("action",1);
        level = getIntent().getIntExtra("level",0);
        id = getIntent().getStringExtra("id");//搜索需要的大类id

        int type = getIntent().getIntExtra("type", 0);
        for(int i = 0; i <  types.length; i++){
            if(types[i] != type)
                continue;
            lastPosition = i;
            break;
        }

        searchWindow = new SearchPopuWindow(this);
        searchWindow.setSearchRemindCallback(new SearchPopuWindow.SearchRemindCallback() {
            @Override
            public void showRemindPopWindow() {
                showSearchWindow();
            }
        });
        clearHistoryDialog = new CommDialog(this);
        clearHistoryDialog.setContent("是否清空搜索历史？");
        clearHistoryDialog.setLeft("取消");
        clearHistoryDialog.setRight("确定");
        clearHistoryDialog.setRightListener(this);

        initSearchHistoryRv();
        initSearLayout();

        searchEdit.setHint("请输入关键字");
        inputManager = (InputMethodManager) searchEdit.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        searchEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                handSearch=true;
                hideSearchWindow();//隐藏搜索框
                if(actionId== EditorInfo.IME_ACTION_SEARCH){
                    handSearch();
                }
                return false;
            }
        });

        searchEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            @Override
            public void afterTextChanged(Editable s) {
                if(s.length() == 0) {
                    getHistoryFromDb();
                    delSearchIcon.setVisibility(View.GONE);
                    hideSearchWindow();
                } else {
                    delSearchIcon.setVisibility(View.VISIBLE);
                    if(searchHistoryRv.getTag() != null){
                        searchHistoryRv.setTag(null);
                    } else {
                        showSearchWindow();
                        searchWindow.searchKeyWord(s.toString());
                    }
                }
            }
        });

        searchWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if(searchEdit.getText().toString().length() > 0)
                    hideSoftAndEdit();
            }
        });

        searchWindow.setOnItemLisertern(new SearchPopuWindow.OnSearchItemListener() {
            @Override
            public void onItemListener(String key) {
                searchHistoryRv.setTag(key);
                searchEdit.setText(key);
                searchEdit.setSelection(key.length());
                handSearch();
                searchWindow.dismiss();
            }
        });

        searchBgView.init(setSearchBgViewType());
        searchBgView.setHistoryItemClickListener(new SearchBgView.OnSearchClickListener() {
            @Override
            public void onSearchClick(String keyWord) {
                searchHistoryRv.setTag(keyWord);
                searchEdit.setText(keyWord);
                searchEdit.setSelection(keyWord.length());
                handSearch();
            }
        });

        searchEdit.setOnClickListener(this);
        searchGoback.setOnClickListener(this);
        cancleSearch.setOnClickListener(this);
        delSearchIcon.setOnClickListener(this);
        voiceInputIcon.setOnClickListener(this);
        searchActivity.setOnClickListener(this);
        searchHistoryTv.setOnClickListener(this);

        searchHistorys = new ArrayList<>();
        saveDbOnSubscribe = new OnSubscribe<List<SearchKey>>() {
            @Override
            public void call(Subscriber<? super List<SearchKey>> subscriber) {
                SearchKey key = null;
                for(SearchKey searchKey : searchHistorys){
                    if(searchEdit.getText().toString().equals(searchKey.getName())){
                        searchKey.setSearchTime(System.currentTimeMillis());
                        key = searchKey;
                        break;
                    }
                }
                if(key == null) {
                    key = new SearchKey();
                    key.setName(searchEdit.getText().toString());
                    key.setSearchTime(System.currentTimeMillis());
                    searchHistorys.add(key);
                }
                DBHelper.getInstance().saveOrUpdate(key);
                subscriber.onNext(searchHistorys);
            }
        };
        readDbObserver = new Observer<List<SearchKey>>(){
            @Override
            public void onCompleted() {
                if(searchHistorys == null)
                    return;
                if(searchHistorys.size() > 1)
                    Collections.sort(searchHistorys, searchHistorys.get(0));
                searchHistoryAdapter.updateAdapter(searchHistorys);
//                if(searchHistorys.size() == 0){
//                    searchHistoryView.setVisibility(View.GONE);
//                    startSearch.setVisibility(View.VISIBLE);
//                } else if(startSearch.getVisibility() == View.VISIBLE){
//                    searchHistoryView.setVisibility(View.VISIBLE);
//                    startSearch.setVisibility(View.GONE);
//                }
            }
            @Override
            public void onError(Throwable e) {
                if(searchHistorys != null)
                    searchHistorys.clear();
                onCompleted();
            }
            @Override
            public void onNext(List<SearchKey> data) {
                if(data != null)
                    searchHistorys = data;
            }
        };
        getHistoryFromDb();
        final String searchKey = getIntent().getStringExtra("key");
        if(searchKey != null) {
            searchHistoryRv.setTag(searchKey);
            searchEdit.setText(searchKey);
            searchEdit.setSelection(searchKey.length());
            showFragment();
        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if(searchKey != null){
                    handSearch();
                } else{
                    MyUtil.startKeyword(SearchActivity.this, searchEdit);
                }
            }
        }, 500);
    }

    protected int setSearchBgViewType(){
        return 0;
    }

    private void initSearchHistoryRv(){
        searchHistoryAdapter = new SearchHistoryAdapter(this, new ArrayList<SearchKey>());
        searchHistoryAdapter.setItemActionHappen(new SearchHistoryAdapter.ItemActionHappen() {
            @Override
            public void onItemClick(int position) {
                String searchKey = searchHistorys.get(position).getName();
                searchHistoryRv.setTag(searchKey);
                searchEdit.setText(searchKey);
                searchEdit.setSelection(searchKey.length());
                handSearch();
            }
            @Override
            public void onItemDelete(int position) {
//                SearchKey removeKey = searchHistorys.remove(position);
//                searchHistoryAdapter.updateAdapter(searchHistorys);
//                if(searchHistorys.size() == 0) {
//                    searchHistoryView.setVisibility(View.GONE);
//                    startSearch.setVisibility(View.VISIBLE);
//                }
//                DBHelper.getInstance().delete(removeKey);
            }
        });
        searchHistoryRv.setHasFixedSize(true);
        searchHistoryRv.setAdapter(searchHistoryAdapter);
        searchHistoryRv.setLayoutManager(new LinearLayoutManager(this){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
    }

    private void handSearch(){
        showFragment();
        hideSoftAndEdit();
        saveKeyWordToDb();
        if(curKey!=null){
            clearSearchResult();
            ((SearchDetailFragment)fragments.get(pager.getCurrentItem())).doSearch();
        }
    }

    /**
     * 保存  搜索关键字入sqlite做搜索历史记录
     */
    private void saveKeyWordToDb() {
        if(searchEdit.getText().toString().trim().length() == 0)
            return;
//        Observable.create(saveDbOnSubscribe)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(readDbObserver);
        searchBgView.addSearchKeyWord(searchEdit.getText().toString());
    }

    /**
     * 从 sqlite 中取出搜索历史记录
     * @return
     */
    private void getHistoryFromDb(){
//        DBHelper.getInstance().findAll(SearchKey.class, readDbObserver);
    }

    /**
     * 显示搜索内容fragment
     */
    protected void showFragment(){
//        searchHistoryView.setVisibility(View.GONE);
//        startSearch.setVisibility(View.GONE);
        searchBgView.setVisibility(View.GONE);
        content.setVisibility(View.VISIBLE);
        recycleView.smoothScrollToPosition(pager.getCurrentItem());
    }

    /**
     * 隐藏搜索内容fragment
     */
    protected void hideFragment(){
//        if(searchHistorys == null || searchHistorys.size() == 0) {
//            searchHistoryView.setVisibility(View.GONE);
//            startSearch.setVisibility(View.VISIBLE);
//        } else{
//            searchHistoryView.setVisibility(View.VISIBLE);
//            startSearch.setVisibility(View.GONE);
//        }
        searchBgView.setVisibility(View.VISIBLE);
        content.setVisibility(View.GONE);
        // 清空搜索结果
        clearSearchResult();
    }

    private void clearSearchResult(){
        for(Fragment fragment : fragments){
            ((SearchDetailFragment)fragment).clearList();
        }
    }

    protected void initSearLayout() {
        getHeadLines();
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        attentAdapter = new AttentionAdapter(headLines, mContext);
        recycleView.setLayoutManager(manager);
        recycleView.setAdapter(attentAdapter);
        recycleView.setItemAnimator(new DefaultItemAnimator());
        setFragment();
    }

    private void getHeadLines() {
        int size = itemNames.length;
        List<HeadLine> list = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            HeadLine headLine = new HeadLine();
            headLine.setTypeName(itemNames[i]);
            headLine.setTypeId(types[i] + "");
            list.add(headLine);
        }
        headLines=list;
    }

    private void setFragment(){
//        pager.setOffscreenPageLimit(0);
        if (headLines != null && headLines.size() > 0) {
            headLines.get(0).setCheck(true);//默认选中第一个
            attentAdapter.update(headLines);
            int size = headLines.size();
            fragments = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                SearchDetailFragment fragment;
                if(types[i] == 15) {      // 界面
                    fragment = new SearchDetailUiFragment();
                } else if(types[i] == 11 || types[i] == 17 || types[i] == 21) { // 全民推荐，每日评说，行业大观察
                    fragment = new SearchRecommendFragment();
                    ((SearchRecommendFragment)fragment).setSearchType(types[i]);
                } else if(types[i] == 16) {
                    fragment = new SearchTeamCircleFragment();
                } else if(types[i] == 3 || types[i] == 4 || types[i] == 8){     // 产品，公司，人物
                    fragment = new SearchAttentionFragment();
                } else {
                    fragment = new SearchDetailFragment();
                }

                fragment.setLabel(headLines.get(i).getTypeId());
                fragment.setType(types[i]);
                fragment.setInfoId(infoId);
                fragment.setAction(action);
                fragment.setLevel(level);
                fragment.setSearchId(id);
                switch(types[i]){
                    case 3:     // 公司
                    case 4:     // 人物
                    case 8:     // 产品
                    case 9:     // 主题   ->  关注
                        setSearchData(fragment, null, null, types[i]);
                        break;
                    case 11:    // 全民推荐
                    case 14:    // 报告
                    case 15:    // 界面   ->  收藏
                        setSearchData(fragment, null, null, types[i]);
                        break;
                }
                fragments.add(fragment);
            }
            pager.init(recycleView, attentAdapter, getSupportFragmentManager(), fragments);
            pager.setPagerChangedListener(new TabHostWrapPagerView.PagerChangedListener() {
                @Override
                public void pagerChanged(int position) {
                    lastPosition = position;
                    SearchDetailFragment fragment = (SearchDetailFragment) fragments.get(position);
                    if(!fragment.checkIsSearchSuccess())
                        fragment.doSearch();
                }
            });
            tabView.setTabItems(itemNames);
            tabView.setupWithViewPager(pager);
            if(lastPosition >= 0 && lastPosition < fragments.size()){
                headLines.get(lastPosition).setCheck(true);
                pager.setCurrentItem(lastPosition);
            }
        }
    }

    protected void setSearchData(SearchDetailFragment fragment, String action, String id, int type){
        fragment.setAction(action);
        fragment.setId(id);
        fragment.setWebType(type);
    }

    public int getType(){
       int curPostion = pager.getCurrentItem();
        return types[curPostion];
    }
    /**
     * 获取关键字
     * @return
     */
    public String getKeyWord(){
        curKey =  searchEdit.getText().toString();
        return curKey;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.search_goback:
            case R.id.cancle_search:
                hideSoftAndEdit();
                onBackPressed();
                break;
            case  R.id.search_del:
                searchEdit.setText("");
                hideFragment();
                hideSoftAndEdit();
                break;
            case R.id.search_voice_input:
                openVoiceInput();
                break;
            case R.id.search:
//                showSearchWindow();
                break;
            case R.id.activity_search:
                    hideSearchWindow();
                break;
            case R.id.search_history_clear:
                clearHistoryDialog.show();
                break;
            case R.id.right_btn:
                DBHelper.getInstance().dropTable(SearchKey.class);
//                searchHistoryView.setVisibility(View.GONE);
//                startSearch.setVisibility(View.VISIBLE);
                searchHistorys.clear();
                break;
            default:
                break;
        }
    }

    /**
     * 显示搜索框
     */
    private void showSearchWindow(){
        if (searchWindow.isEmpty()) {
            if (searchWindow.isShowing())
                searchWindow.dismiss();
            return;
        }
        if(!searchWindow.isShowing()){
            if(!handSearch){
                searchWindow.showAsDropDown(headLayout);
            }else{
                handSearch=false;
            }
        }
    }

    /**
     * 隐藏搜索框
     */
    private void hideSearchWindow(){
        if(searchWindow.isShowing()) {
            searchWindow.dismiss();
            searchWindow.clearList();
        }
    }

    private static final int REQUEST_RECORD_AUDIO_CODE = 0x01;
    /* 打开语音输入 */
    private void openVoiceInput(){
        if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
                && (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED)){
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, REQUEST_RECORD_AUDIO_CODE);
        } else {
            searchEdit.setText("");
            VoiceInputUtils.getInstance(mContext).startInput(new VoiceInputUtils.VoiceInputCallback() {
                @Override
                public void onResult(String result) {
                    if(result.trim().length() > 0) {
                        handSearch=true;
                        hideSearchWindow();

                        searchHistoryRv.setTag(result);
                        searchEdit.setText(result);
                        searchEdit.setSelection(result.length());
                        handSearch();
                    }
                }
                @Override
                public void onChanged(String str) {
                    searchEdit.setText(searchEdit.getText().toString()+str);
                    searchEdit.setSelection(searchEdit.getText().length());
                }
                @Override
                public void onError(SpeechError speechError) {}
            });
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_RECORD_AUDIO_CODE && grantResults.length > 0){
            if(grantResults[0] != PackageManager.PERMISSION_GRANTED)
                ToasUtil.toast(mContext, "抱歉，你没有权限访问打开麦克风，请到设置中开启麦克风权限后重试");
            else
                openVoiceInput();
        }
    }

    /**
     * 隐藏软键盘
     */
    public void hideSoftAndEdit() {
        if (inputManager!=null&&inputManager.isActive())
            inputManager.hideSoftInputFromWindow(searchEdit.getWindowToken(), 0);
    }

    @Override
    public void onBackPressed() {
//        if(searchWindow.isShowing()){
//            getHistoryFromDb();
//            hideSearchWindow();
//        } else if(content.getVisibility() == View.VISIBLE){
//            hideFragment();
//            showSearchWindow();
//        }else {
//            super.onBackPressed();
//        }
        super.onBackPressed();
    }

    public interface Callback{
        void done();
    }

    @Override
    protected void onDestroy() {
        searchBgView.saveSearchHistoryToCache();
        LocalBroadcastManager.getInstance(mContext)
                .sendBroadcast(new Intent(LocalBroadCast.GET_ATTION_DATA_BROAD));
        super.onDestroy();
    }
}
